<?php
	
	if(!$_SESSION["username"]){
		//not logged in
		header("location:login.php");
	}
	
	if ($_SERVER['REQUEST_METHOD'] == 'POST'){
		$file_error="";
		$file_type="";
		if(isset($_FILES['file']['error'])){
			$file_name = $_FILES['file']['name']; // file name
			$file_path  = $_FILES['file']['tmp_name']; // actual location
			$file_size  = $_FILES['file']['size']; // file size
			$file_type  = $_FILES['file']['type']; // mime type of file
			$file_error  = $_FILES['file']['error']; // error
		}

		$file_data = '';
		if (!empty($file_path)){
			$file_data = base64_encode(@fread(fopen($file_path, 'r'), filesize($file_path) ) );
		}

		if ($file_error != ""){
			echo '<div id="error" style="display:block;"><a href="index.php">';
			switch ($file_error) {
			
				case UPLOAD_ERR_NO_FILE:
					if (empty($file_data)){
						echo 'You must select a file to upload.';
					}
					break;		
			
				case UPLOAD_ERR_FORM_SIZE:
				case UPLOAD_ERR_INI_SIZE:
					echo 'The file you have attempted to upload is too large.';
					break;
					
				case UPLOAD_ERR_PARTIAL:
					echo 'An error occured while trying to recieve the file. Please try again.';
					break;
					
				case UPLOAD_ERR_EXTENSION:
					echo 'File type must be excel (.xls).';
					break;
			}
			echo '</a></div>';
		}

		if( !empty($file_path)){
			// only MS Excel file is accepted.
			if( !($file_type=="application/vnd.ms-excel") ){
				echo '<div id="error" style="display:block;"><a href="index.php">';
				echo 'File type must be excel (.xls).';
				echo '</a></div>';
			} else {
				$target_path = "temp/";
				$target_path .= basename($file_name);

				if(move_uploaded_file($file_path, $target_path)) {
					echo '<div id="error" style="display:block;background:#9F9;color:#777;"><a href="index.php">';
					echo "The file ".basename($file_name)." has been uploaded";
					echo '</a></div>';
					header("location:".$_SERVER['HTTP_REFERER']."?message=import");
				} else {
					echo '<div id="error" style="display:block;"><a href="index.php">';
					echo "There was an error uploading the file, please try again!";
					echo '</a></div>';
				}
			}
		}
	}
?>